package se.kayarr.cardplay.shared;

import java.util.Locale;

import lombok.Getter;

public class ClampedValue {
	@Getter private int min;
	@Getter private int max;
	@Getter private int current;
	
	public ClampedValue(int max) {
		this(max, 0);
	}
	
	public ClampedValue(int max, int current) {
		this(0, max, current);
	}
	
	public ClampedValue(int min, int max, int current) {
		this.min = min;
		this.max = max;
		this.current = current;
		
		clampValue();
	}
	
	public void setMin(int min) {
		this.min = min;
		
		clampValue();
	}
	
	public void setMax(int max) {
		this.max = max;
		
		clampValue();
	}
	
	public void setCurrent(int current) {
		this.current = current;
		
		clampValue();
	}
	
	private void clampValue() {
		if(min > max) {
			int tmp = min;
			min = max;
			max = tmp;
		}
		
		if(current < min) current = min;
		if(current > max) current = max;
	}
	
	public void addPercent(double percent) {
		addAmount( (int)((max-min) * (percent/100.0)) );
	}
	
	public void removePercent(double percent) {
		removeAmount( (int)((max-min) * (percent/100.0)) );
	}
	
	public void addAmount(int amount) {
		if(amount < 0) removeAmount(-amount);
		else setCurrent(current + amount);
	}
	
	public void removeAmount(int amount) {
		if(amount < 0) addAmount(-amount);
		else setCurrent(current - amount);
	}
	
	public boolean isAtMin() {
		return current == min;
	}
	
	public boolean isAtMax() {
		return current == max;
	}
	
	public void setToMax() {
		setCurrent(getMax());
	}
	
	public void setToMin() {
		setCurrent(getMin());
	}
	
	public boolean isBelowPercent(double percent) {
		return getPercent() < percent;
	}
	
	public boolean isAbovePercent(double percent) {
		return getPercent() > percent;
	}
	
	public boolean isBelowOrEqualPercent(double percent) {
		return !isAbovePercent(percent);
	}
	
	public boolean isAboveOrEqualPercent(double percent) {
		return !isBelowPercent(percent);
	}
	
	public double toMultiplier() {
		return (current-min)/(double)(max-min);
	}
	
	public double getPercent() {
		return (toMultiplier() * 100.0);
	}
	
	public void setPercent(double percent) {
		setCurrent( min + (int)((max-min) * (percent/100.0)) );
	}
	
	public String toInlinedString() {
		StringBuilder builder = new StringBuilder();
		
		if(min == 0) //Default format for when minimum is 0: current/max
			builder.append(current).append('/').append(max);
		else //When minimum is non-zero: min~current~max
			builder.append(min).append("~").append(current).append("~").append(max);
		
		builder.append(", ").append(String.format(Locale.ENGLISH, "%.1f", getPercent())).append('%');
		return builder.toString();
	}
	
	public String toString() {
		return new StringBuilder().append('[').append(toInlinedString()).append(']').toString();
	}
}
